import { ElMessage } from "element-plus";
import { ElNotification } from 'element-plus'
import useConfigStore from "@/store/config";
import useSaveStore from '@/store/save'
import ls from "@/lib/ls";
import dayjs from "dayjs";
import { formatDate } from "@/utils/chenhao";
import router from '@/router'
let websocket = null; // 用于存储实例化后websocket
let rec; // 断线重连后，延迟5秒重新创建WebSocket连接  rec用来存储延迟请求的代码
let setIntervalName = null; // 定时器
let loacalUrl = "";
// 创建websocket
function creatWebSocket(wsUrl) {
  console.log("websocket==================");
  // 判断当前浏览器是否支持WebSocket
  if ("WebSocket" in window) {
    console.log("当前浏览器支持 WebSocket");
  } else if ("MozWebSocket" in window) {
    console.log("当前浏览器支持 MozWebSocket");
  } else {
    console.log("当前浏览器不支持 WebSocket");
  }
  try {
    initWebSocket(wsUrl); // 初始化websocket连接
  } catch (e) {
    console.log("尝试创建连接失败");
    reConnect(wsUrl); // 如果无法连接上 webSocket 那么重新连接！可能会因为服务器重新部署，或者短暂断网等导致无法创建连接
  }
}
// 初始化websocket
function initWebSocket(wsUrl) {
  if (wsUrl && wsUrl != "") loacalUrl = wsUrl;
  else wsUrl = loacalUrl;
  console.log("wsUrl", wsUrl);
  
  websocket = new WebSocket(wsUrl);
  const configStore = useConfigStore();
  const userInfo = ls.get("USER_INFO");
  let shopInfo = {
    msgType: "login",
    msgPlatform: 1, //1：电脑 2：服务员点单 3：小程序 4：微信公众号 5：微信企业号
    msgContent: {
      // code: ls.get("WEB_CODE"),
      orgCode: userInfo.orgCode,
      orgName: userInfo.orgName,
      userCode: userInfo.userCode,
      userName: userInfo.userName,
    },
  };
  // console.log("websocket:", websocket);
  websocket.onopen = function () {
    websocketOpen();
    
    sendWebSocket(shopInfo); // 发送登录信息
    setIntervalName = setInterval(function () {
      // 发送心跳
      // console.log(22222);
      console.log(shopInfo);
      shopInfo.msgType = "heartbeat";
      sendWebSocket(shopInfo);
      //sendWebSocket('heartbeat');
    }, 10000); // 10000毫秒等于10秒
  };
  //   // 接收
  websocket.onmessage = function (e) {
    websocketonmessage(e);
  };
  // 连接发生错误
  websocket.onerror = function () {
    console.log("WebSocket连接发生错误");
    //     isConnect = false; // 连接断开修改标识
    reConnect(wsUrl); // 连接错误 需要重连
  };
  websocket.onclose = function (e) {
    websocketclose(e);
    clearInterval(setIntervalName)
    reConnect(wsUrl)
  };
}
// 定义重连函数
let reConnect = (wsUrl) => {
  console.log(websocket)
  console.log(websocket.readyState);
  console.log(WebSocket.OPEN);
  
  if(websocket && websocket.readyState === WebSocket.OPEN) return;
  const configStore = useConfigStore();
  console.log("尝试重新连接");
  if (configStore.isConnected) return; // 如果已经连上就不在重连了
  rec && clearTimeout(rec);
  rec = setTimeout(function () {
    // 延迟15秒重连  避免过多次过频繁请求重连
    creatWebSocket(wsUrl);
  }, 15000);
};
// 创建连接
function websocketOpen() {
  const configStore = useConfigStore();
  console.log("连接成功");
  configStore.connect(); // 修改连接状态
}
// 数据接收
function websocketonmessage(e) {
  const configStore = useConfigStore();
  const saveStore = useSaveStore()
  const today = dayjs().format("YYYY-MM-DD");
  let curTableDate = configStore.curTableDate;
  const data = JSON.parse(e.data); // 解析JSON格式的数据
  // console.log(111);
  // debugger;
  console.log("websocketonmessage   data", data, configStore.curTableDate);
  //
  if(data.msgType == "Notice"){
    if (data.subMsgType == "CallRoom") {
     const { msgContent } = data;
     configStore.curTable.forEach((item) => {
       if (item.roomCode == msgContent.roomCode) {
         item.isCall = msgContent.isCall
         console.log(item);
       }
       
       
     });
   }
 }
  if (
    data.msgType == "login" ||
    data.msgType == "offline"
  ){ }
  // 心跳接收
  else if(data.msgType == "heartbeat"){
    configStore.currentTime.time = data.cruuentTime
    const curPage = router.currentRoute.value.fullPath
    const sesssion = data.msgContent.goodsVersion
    let goodsCodeList = []
    if(data.msgContent.goodsCodeList){
      goodsCodeList = data.msgContent.goodsCodeList.split(',')
    }
   
      if(ls.get('GOOD_SESSION')){
        
        if(sesssion != ls.get('GOOD_SESSION')){
          configStore.isGoodChange.id ++ // 通知页面重新渲染
          configStore.isGoodChange.goodsCode = []
          ls.set('GOOD_SESSION',sesssion)
        }
      }else{
        ls.set('GOOD_SESSION',sesssion)
      }
  }
  else if(data.msgType == "GoodsPrice"){
    // let goodsCodeList = []
    // if(data.msgContent){
    //   goodsCodeList = data.msgContent
    // }
    // if(cartStore.cartList){ // 购物车有被沽清的商品
    //  if(hasCodeInTargetArray(cartStore.cartList,goodsCodeList)){
    //      showToast('购物车商品已售罄,请重新点单')
    //      cartStore.ClearCart()
    //  }
    // }
    //   const msgContent = data.msgContent
    //   msgContent.forEach(item=>{
    //     if(item.delete){ // 沽清
    //       console.log('沽清');
    //         configStore.productList.forEach(obj => {
    //           obj.children.forEach(vi=>{
    //             if(vi.goodsCode === item.goodsCode){
    //                 vi.isEstmClear = '1'
    //                 vi.priceList[0].isEstmClear = '1'
    //             }
    //           })
    //         });
    //         configStore.goodsList.forEach(obj=>{
    //           if(obj.goodsCode === item.goodsCode){
    //               obj.isEstmClear = '1'
    //               obj.priceList[0].isEstmClear = '1'
    //           }
    //         })
    //         console.log(configStore.productList,configStore.goodsList);
            
    //     }else{ // 价格变动或反沽清
    //       console.log('价格变动或反沽清');
    //       configStore.productList.forEach(obj => {
    //         obj.children.forEach((vi,index)=>{
    //           if(vi.goodsCode === item.goodsCode){
                
    //             obj.children[index] = item;
                  
    //           }
    //         })
    //       });
    //       configStore.goodsList.forEach((obj,index)=>{
    //         if(obj.goodsCode === item.goodsCode){
    //           configStore.goodsList[index] = item;
    //         }
    //       })
        
          
    //     }
         
    //   })

      configStore.isGoodChange.id ++ // 通知页面重新渲染
      console.log(data.msgContent);
      
      configStore.isGoodChange.goodsCode = data.msgContent
  }
   else {
    if (data.msgReceivePage == "Room") {
      const { msgContent } = data;
      setTypeList(msgContent.roomStateSummary);
      console.log('Room :>> ', data.msgReceivePage);
      // 清台 变成空闲中
      if (data.subMsgType == "ClearRoom") {
        if (curTableDate == today) {
          configStore.curTable.forEach((item) => {
            if (item.roomCode == msgContent.roomCode) {
              console.log("找到桌子 :>> ", item, msgContent);
              Object.assign(item, msgContent);
            }
          });
        }
      }
      // 开台 变成使用中
      else if (data.subMsgType == "OpenRoom") {
        if (curTableDate == today) {
          configStore.curTable.forEach((item) => {
            if (item.roomCode == msgContent.roomCode) {
              console.log("找到桌子 :>> ", item, msgContent);
              Object.assign(item, msgContent);
            }
          });
        }
      }
      // 转台
      else if (data.subMsgType == "TurnRoom") {
        const reserveTime = formatDate(
          "YY-MM-DD",
          msgContent.reserveInfo.reserveTime
        );
        if (curTableDate == reserveTime) {
          configStore.curTable.forEach((item) => {
            // 旧桌
            if (item.roomCode == msgContent.oldRoom.roomCode) {
              console.log("找到旧桌子 :>> ", item, msgContent);
              Object.assign(item, msgContent.oldRoom);
            }
            // 新桌
            if (item.roomCode == msgContent.newRoom.roomCode) {
              console.log("找到新桌子 :>> ", item, msgContent);
              Object.assign(item, msgContent.newRoom);
            }
          });
        }
      }
      // 复台
      else if (data.subMsgType == "ResetRoom") {
        if (curTableDate == today) {
          configStore.curTable.forEach((item) => {
            if (item.roomCode == msgContent.roomCode) {
              console.log("找到旧桌子 :>> ", item, msgContent);
              Object.assign(item, msgContent);
            }
          });
        }
      }
      // 预订
      else if (data.subMsgType == "ReserveRoom") {
        const reserveTime = formatDate(
          "YY-MM-DD",
          msgContent.reserveInfo.reserveTime
        );
        if (curTableDate == reserveTime) {
          configStore.curTable.forEach((item) => {
            if (item.roomCode == msgContent.roomInfo.roomCode) {
              console.log("找到旧桌子 :>> ", item, msgContent);
              let obj = {
                ...msgContent.roomInfo,
                ...msgContent.reserveInfo,
                reserveCode: msgContent.reserveInfo.itemCode,
              };
              Object.assign(item, obj);
            }
          });
        }
      }
      // 取消预订
      else if (data.subMsgType == "CancelReserveRoom") {
        const reserveTime = formatDate(
          "YY-MM-DD",
          msgContent.reserveInfo.reserveTime
        );
        if (curTableDate == reserveTime) {
          configStore.curTable.forEach((item) => {
            if (item.roomCode == msgContent.roomInfo.roomCode) {
              console.log("找到旧桌子 :>> ", item, msgContent);
              let obj = { ...msgContent.roomInfo, ...msgContent.reserveInfo };
              Object.assign(item, obj);
            }
          });
        }
      }
      // 维修
      else if (data.subMsgType == "RepairRoom") {
        if (curTableDate == today) {
          configStore.curTable.forEach((item) => {
            if (item.roomCode == msgContent.roomCode) {
              console.log("找到桌子 :>> ", item, msgContent);
              // 变成维修中
              if (msgContent.repairState == "0") {
                item.roomStateDesc = "维修中";
                item.roomState = "-1";
              }
              // 变成正常
              else if (msgContent.repairState == "1") {
                item.roomStateDesc = "空闲中";
                item.roomState = "0";
              }
            }
          });
        }
      }
      // 锁台
      else if (data.subMsgType == "LockRoom") {
        if (curTableDate == today) {
          configStore.curTable.forEach((item) => {
            if (item.roomCode == msgContent.roomCode) {
              console.log("找到桌子 :>> ", item, msgContent);
              // 变成锁台
              if (msgContent.lockState == "1") {
                item.isLock = true;
              }
              // 变成正常
              else if (msgContent.lockState == "0") {
                item.isLock = false;
              }
            }
          });
        }
      }
    }
    // 订单相关
    else if (data.msgReceivePage == "Order") {
      const { msgContent } = data;
      if (msgContent.roomStateSummary) {
        setTypeList(msgContent.roomStateSummary);
      }
      // console.log('Room :>> ', configStore.curTable);
      // 清台 变成空闲中
      if (data.subMsgType == "OrderAdd") {
        if (curTableDate == today) {
          configStore.curTable.forEach((item) => {
            if (item.roomCode == msgContent.roomCode) {
              console.log("找到桌子 :>> ", item, msgContent);
              Object.assign(item, {
                ...msgContent,
                unPayAmt: msgContent.totalAmt,
              });
            }
          });
        }
      } else if (data.subMsgType == "CheckOut") {
        if (curTableDate == today) {
          configStore.curTable.forEach((item) => {
            if (item.roomCode == msgContent.roomCode) {
              console.log("找到桌子 :>> ", item, msgContent);
              Object.assign(item, { ...msgContent });
            }
          });
        }
        // 在结账页面的时候提示已支付
        const payTableInfo = ls.get('payTableInfo')
        console.log('payTableInfo :>> ', payTableInfo);
      }
    }
    //呼叫相关的处理
    else if (data.msgReceivePage == "User") {
      const msg = JSON.parse(e.data).msgContent
      const type = JSON.parse(e.data).subMsgType
      switch (msg.memberMsgType) {
        case '001': // 客户呼叫
          msg.content = '客户呼叫'
          break;

        case '002': // 存酒确认
          msg.content = '存酒确认'
          break;
      }
      const id = msg.messageId
      let arr = ls.get('MSG_LIST')
      if (!arr) {
        arr = []
      }
      console.log(arr);
      let foundIndex1 = -1
      if (type == 'CallWaiter') {
        // 添加推送
        arr.push(msg)
        ls.set('MSG_LIST', arr)
      } else {
        // 处理推送
        foundIndex1 = arr.findIndex(obj => obj.messageId == id);
        if (foundIndex1 !== -1) {
          arr.splice(foundIndex1, 1);
          ls.set('MSG_LIST', arr)
        }
      }


      // 如果有id相同的
      if (type == 'CallWaiter') {
        // 添加推送
          saveStore.msgList.push(msg)
          ElNotification({
            title: '呼叫',
            message:'房台'+ msg.roomName + msg.content,
            type: 'success',
          })
      }else{
        // 处理推送
        const foundIndex = saveStore.msgList.findIndex(obj => obj.messageId == id);
        if (foundIndex !== -1) {
          saveStore.msgList.splice(foundIndex, 1);
          ElNotification({
            title: '呼叫',
            message: '处理呼叫请求',
            type: 'success',
          })
        }
      }

      // let sss="sss"
    }
    else if (data.msgReceivePage == "Queue") {
      const msg = JSON.parse(e.data).msgContent
      const type = JSON.parse(e.data).subMsgType
      // saveStore.queFirst.push()

      if(type == 'AddQueue'){
        if(saveStore.queList.length < 3){
          saveStore.queList.push(msg)
        }
      }else if (type == 'PassQueue' ||type == 'SeatQueue'){

        saveStore.queState.id ++
        console.log(saveStore.queState);
      }

    
    }
    else if (data.msgReceivePage == "GoodsPrice") {
      alert(JSON.stringify(data.msgContent))
    }
    // if (data.msgContent) {
    //   if (data.msgContent.code) {
    //     ls.set('WEB_CODE', data.msgContent.code)
    //   }
    // }
    // 下面的判断则是后台返回的接收到的数据  如何处理自己决定
    // if (data.code === 400) {
    //   console.log("数据接收", data.msg);
    //   ElMessage({
    //     showClose: true,
    //     message: data.msg,
    //     type: 'warning',
    //   })
    // } else if (data.code === 404) {
    //   ElMessage({
    //     showClose: true,
    //     message: data.msg,
    //     type: 'warning',
    //   })
    // } else if (data.code === 0) {
    //   ElMessage({
    //     showClose: true,
    //     message: "连接成功",
    //     type: 'success',
    //   })
    // } else if (data.code === 200) {
    //   ElMessage({
    //     showClose: true,
    //     message: data.msg,
    //     type: 'success',
    //   })
    //   // 成功后的相应处理  此处成功后播放音乐
    //   // const audio = new Audio('./tipMusic.mp3');
    //   // audio.play();
    // } else {
    //   ElMessage({
    //     showClose: true,
    //     message: data.msg,
    //     type: 'error',
    //   })
    //   // 延时5秒后刷新页面
    //   // setTimeout(() => {
    //   //   location.reload();
    //   // }, 1000);
    // }
    // let data = JSON.parse(decodeUnicode(e.data))
  }

}
// 关闭
function websocketclose(e) {
  const configStore = useConfigStore();
  console.log(e);
  configStore.disconnect(); // 修改连接状态
  console.log("connection closed (" + e.code + ")");
}
// 数据发送
function websocketsend(data) {

  const configStore = useConfigStore();
  if (websocket && configStore.isConnected) {
    // 检查连接状态
    const sendstr = JSON.stringify(data);
    if (websocket.readyState && websocket.readyState == 3) initWebSocket();
    if (websocket.readyState && websocket.readyState == 1)
      // console.log(sendstr);
    websocket.send(sendstr);
  } else {
    // ElMessage({
    //   showClose: true,
    //   message: "请选择设备连接",
    //   type: "error",
    // });
  }
}
// 实际调用的方法==============
// 发送
function sendWebSocket(data) {
  const configStore = useConfigStore();
  // 如果未保持连接状态 不允许直接发送消息 提示请选择连接设备
  if (!configStore.isConnected) {
    // ElMessage({
    //   showClose: true,
    //   message: "请选择设备连接",
    //   type: "error",
    // });
  } else {
    websocketsend(data);
  }
}
// 关闭
let closeWebSocket = () => {
  if (websocket) {
    websocket.close();
    ElMessage({
      showClose: true,
      message: "设备已关闭",
      type: "success",
    });
  }
};
export { initWebSocket, sendWebSocket, creatWebSocket, closeWebSocket };

const setTypeList = (obj) => {
  const configStore = useConfigStore();
  configStore.typeList.forEach((item) => {
    if (item.name == "全部") {
      item.num = obj.totalCount;
    } else if (item.name == "空闲") {
      item.num = obj.idleCount;
    } else if (item.name == "已预订") {
      item.num = obj.reserveCount;
    } else if (item.name == "使用中") {
      item.num = obj.usedCount;
    } else if (item.name == "未支付") {
      item.num = obj.unPayCount;
    } else if (item.name == "维修中") {
      item.num = obj.repairCount;
    } else if (item.name == "已锁定") {
      item.num = obj.lockCount;
    }
  });
};
